package com.leantech.android.browser.utils

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_FAIL
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_INFO
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_NOTHING
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_SUCCESS
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import splitties.resources.txt

private const val DEFAULT_DELAY = 1500L



fun Fragment.toast(
    text: CharSequence?,
    iconType: Int = ICON_TYPE_NOTHING,
    dismissDelay: Long = DEFAULT_DELAY,
    onDismiss: (() -> Unit)? = null
) {
    requireActivity().toast(text, iconType, dismissDelay, onDismiss)
}


fun Fragment.successToast(
    text: CharSequence?, dismissDelay: Long = DEFAULT_DELAY, onDismiss: (() -> Unit)? = null
) {
    toast(text, ICON_TYPE_SUCCESS, dismissDelay, onDismiss)
}

fun Fragment.infoToast(text: CharSequence?, dismissDelay: Long = DEFAULT_DELAY) {
    toast(text, ICON_TYPE_INFO, dismissDelay)
}


fun Fragment.failToast(text: CharSequence?, dismissDelay: Long = DEFAULT_DELAY) {
    toast(text, ICON_TYPE_FAIL, dismissDelay)
}

fun FragmentActivity.toast(
    text: CharSequence?,
    iconType: Int = ICON_TYPE_NOTHING,
    dismissDelay: Long = DEFAULT_DELAY,
    onDismiss: (() -> Unit)? = null
) {
    text?.also {
        val dialog = QMUITipDialog.Builder(this).setIconType(iconType).setTipWord(it).create(false)

        dialog.show()
        dialog.setOnDismissListener {
            onDismiss?.invoke()
        }

        lifecycleScope.launch {
            delay(dismissDelay)
            dialog.dismiss()
        }
    }
}

fun FragmentActivity.successToast(
    text: CharSequence?, dismissDelay: Long = DEFAULT_DELAY, onDismiss: (() -> Unit)? = null
) {
    toast(text, ICON_TYPE_SUCCESS, dismissDelay, onDismiss)
}

fun FragmentActivity.successToast(
    textRes: Int, dismissDelay: Long = DEFAULT_DELAY, onDismiss: (() -> Unit)? = null
) {
    toast(txt(textRes), ICON_TYPE_SUCCESS, dismissDelay, onDismiss)
}

fun FragmentActivity.infoToast(
    text: CharSequence?, dismissDelay: Long = DEFAULT_DELAY, onDismiss: (() -> Unit)? = null
) {
    toast(text, ICON_TYPE_INFO, dismissDelay, onDismiss)
}


fun FragmentActivity.failToast(
    text: CharSequence?, dismissDelay: Long = DEFAULT_DELAY, onDismiss: (() -> Unit)? = null
) {
    toast(text, ICON_TYPE_FAIL, dismissDelay, onDismiss)
}

fun FragmentActivity.failToast(
    textRes: Int, dismissDelay: Long = DEFAULT_DELAY, onDismiss: (() -> Unit)? = null
) {
    toast(txt(textRes), ICON_TYPE_FAIL, dismissDelay, onDismiss)
}
